<?php

namespace App\Http\Controllers\Api\V4;

use Illuminate\Http\Request;
use App\Http\Controllers\Controller;
use App\Http\Controllers\Weixin\WeixinServiceController AS WeixinService;
use App\Models\V2\MemberModel;
use EasyWeChat\Payment\Order;
use DB;
use App\Http\Controllers\admin_system\LiveController as AdminLiveController;
class WeiXinController extends Controller
{


    /**
     * 获得支付的数据
     * */
    public function get_pay_data(Request $request){
        header("Access-Control-Allow-Origin: *");
        $key        = $request->input('key');
        $mobile     = $request->input('mobile');
        $goodsType  = $request->input('goodsType');
        $goodsId    = $request->input('goodsId');
        $goodsNumber= $request->input('goodsNumber',1);

        $data   = [
            'key'       => [$key,1001,'缺少KEY'],
            'mobile'    => [$mobile,1002,'缺少手机号'],
            'type'      => [$goodsType,1003,'缺少类型'],
            'id'        => [$goodsId,1004,'缺少产品ID']
        ];

        $result = $this->check_params($data);
        if(!$result->status)
        {
            return apiData()->send($result->code,$result->message);
        }

        $memberModel    = new MemberModel();
        $memberInfo     = $memberModel->get_member_info_by_mobile_key($mobile,$key);
        if(!$memberInfo)
        {
            return apiData()->send(2001,'用户不存在');
        }
        $wxService  = new WeixinService();
        $app        = $wxService->get_oauth_client_app();
        $payment    = $app->payment;


        //获得订单信息
        /*$data = [
            'payDesc'   => '打赏', //支付描述
            'money'     => $money,//打赏金额
            'tradeNo'   => 'xxx'  //订单号
            'callback'  => url('api/v4/livePayCallback')//支付回调
        ];*/

        switch($goodsType)
        {
            default:
                if("live" == substr($goodsType,0,4))
                {
                    $orderData  = $this->add_live_pay_order(substr($goodsType,6),$goodsId,$goodsNumber);
                }
                break;
        }

        $attributes = [
            'trade_type'       => 'APP', // JSAPI，NATIVE，APP...
            'body'             => $orderData['payDesc'],
            'detail'           => 'xxxxx',
            'out_trade_no'     => $orderData['tradeNo'],
            'total_fee'        => $orderData['money']*100,  // 单位：分
            'notify_url'       => $orderData['callback'],             // 支付结果通知网址，如果不设置则会使用配置里的默认地址
            'attach'           => 'uid='.$memberInfo->UserID.'&gid='.$goodsId."&gtype=".$goodsType
        ];

        //创建一个支付订单
        $order = new Order($attributes);

        //获得支付数据
        $result = $payment->prepare($order);

        if ($result->return_code == 'SUCCESS' && $result->result_code == 'SUCCESS')
        {
            $prepayId = $result->prepay_id;
        }
        else
        {
            return apiData()->send(4001,$result->return_msg);
        }
        $appConfig = $payment->configForAppPayment($prepayId);

        //记录订单
        $wxPayData  = [
            'user_id'   => $memberInfo->UserID,
            'trade_no'  => $orderData['tradeNo'],
            'goods_type'=> $goodsType,
            'goods_id'  => $goodsId,
            'order_money'=>$orderData['money'],
            'created_at'=> date_time()
        ];
        DB::table('wx_app_pay_log')->insert($wxPayData);
        return apiData()
            ->set_data('appPayConfig',$appConfig)
            ->send(200,'ok');
    }




    /**
     * 新增直播支付订单
     * @param $liveId int 直播ID
     * @param $giftId int 赠的礼物的ID
     * @param $number int 礼物的数量
     * */
    private function add_live_pay_order($liveId,$giftId,$number)
    {
        $giftInfo = DB::table('live_gift_list')
            ->where('id',$giftId)
            ->whereNull('deleted_at')
            ->first();

        $money  = $giftInfo->price * $number;
        $data = [
            'payDesc'   => '打赏',
            'money'     => $money,
            'tradeNo'   => create_member_number(),
            'callback'  => url('api/v4/weixin/livePayCallback')
        ];
        return $data;
    }





    /**
     * 微信支付回调
     * */
    public function live_pay_callback(Request $request)
    {
        $weixinService  = new WeixinService();
        $app            = $weixinService->get_oauth_client_app();
        $adminLiveController            = new AdminLiveController();
        $memberModel                    = new MemberModel();

        $GLOBALS['memberModel']         = $memberModel;
        $GLOBALS['adminLiveController'] = $adminLiveController;
        $GLOBALS['wxservice']           = $weixinService;

        $response = $app->payment->handleNotify(function($notify, $successful){
            // 你的逻辑
            $attach     = $notify->attach;
            $attachs    = explode('&',$attach);
            foreach($attachs as $v)
            {
                $values = explode('=',$v);
                $attachs[$values[0]] = $values[1];
            }

            $userId     = $attachs['uid'];
            $goodsId    = $attachs['gid'];
            $memberInfo = $GLOBALS['memberModel']->get_member_info_by_id($userId);
            $goodsInfo  = DB::table('live_gift_list')->where('id',$goodsId)->first();

            $notice     = [
                'rewarder'      => $memberInfo->YourName,
                'rewarderHead'  => change_member_head_img($memberInfo->FilePath1),
                'giftImg'       => env('HOST')."/".$goodsInfo->img_url,
                'giftInfo'      => "打赏了一个".$goodsInfo->name,
            ];


            $GLOBALS['adminLiveController']->send_group_system_notification($notice);

            $tradeNo    = $notify->out_trade_no;    //订单号
            $updateInfo = [
                'pay_time'          => $notify->time_end,
                'transaction_id'    => $notify->transaction_id,
                'pay_money'         => $notify->total_fee,
                'openid'            => $notify->openid,
                'pay_status'        => 1
            ];
            DB::table('wx_app_pay_log')->where('trade_no',$tradeNo)->update($updateInfo);

            return true; // 或者错误消息
        });
        return $response; // Laravel 里请使用：return $response;
    }


}
